//import './urlbase64.js';
import { defineConfig } from "vite";
import merge from "lodash/merge";
import ver from "./ver.mjs";
import { join, dirname } from "path";
import { rmSync } from "fs";

production = process.env.NODE_ENV == "production";

const CI_DIR = "../../../ci/tmp";
if (production) {
	rmSync(CI_DIR, { recursive: true, force: true });
}

const root = dirname(__dirname);

const _merge = (config) => {
	const { build: { outDir }, esbuild: { target } } = config;

	config.build.outDir = production ? CI_DIR : join("../../dist", outDir);

	if (production) {
		config.build.emptyOutDir = false;
	}

	return merge(
		config,
		{
			esbuild: {
				legalComments: "none",
				charset: "utf8",
				treeShaking: true,
				target: target + ver[target].split(".")[0],
			},
			resolve: { alias: { "@": join(root, "src") } },
			//assetsInclude: ["**/*.svg"],
			build: {
				rollupOptions: {
					output: {
						entryFileNames: "[name].js",
						chunkFileNames: production ? "[hash].js" : "[name].js",
						assetFileNames: production ? "[hash].[ext]" : "[name].[ext]",
						//assetFileNames: "[name].[ext]",
					},
				},
			},
		},
	);
};

export default (config) => {
	if (config instanceof Function) {
		var _config = config;
		config =
			(...args) => {
				return _merge(_config(...args));
			};
	} else {
		_merge(config);
	}
	return defineConfig(config);
};
